﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Db4objects.Db4o;
using DonNicky.Db.Db4o.Config.Attributes;

namespace DonNicky.Db.Db4o
{
    [TransparentPersisted]
    public class Db4oTPChildEntity
    {
        [Transient]
        private bool _isParentDeleted = false;
        [Transient]
        private bool _isParentDefined = false;

        public class Dictionary<T, K> : IDictionary<T, K> where K : Db4oTPChildEntity
        {
            private Db4oTPEntity _parent;
            private IDictionary<T, K> _dict;

            public Dictionary(Db4oTPEntity parent) { _parent = parent; _dict = new Db4oTPEntity.Dictionary<T, K>(parent); }

            #region IDictionary<T,K> Members

            public void Add(T key, K value) { _dict.Add(key, value); value._isParentDefined = true; }
            public bool ContainsKey(T key) { return _dict.ContainsKey(key); }
            public ICollection<T> Keys { get { return _dict.Keys; } }
            public bool Remove(T key) { _parent.DeletedChildren.Add(_dict[key]); return _dict.Remove(key); }
            public bool TryGetValue(T key, out K value) { return _dict.TryGetValue(key, out value); }
            public ICollection<K> Values { get { return _dict.Values; } }
            public K this[T key] { get { return _dict[key]; } set { _dict[key] = value; } }

            #endregion

            #region ICollection<KeyValuePair<T,K>> Members

            public void Add(KeyValuePair<T, K> item) { _dict.Add(item); }
            public void Clear()
            {
                foreach (K item in _dict.Values)
                    _parent.DeletedChildren.Add(item);
                _dict.Clear(); 
            }
            public bool Contains(KeyValuePair<T, K> item) { return _dict.Contains(item); }
            public void CopyTo(KeyValuePair<T, K>[] array, int arrayIndex) { _dict.CopyTo(array, arrayIndex); }
            public int Count { get { return _dict.Count; } }
            public bool IsReadOnly { get { return _dict.IsReadOnly; } }
            public bool Remove(KeyValuePair<T, K> item) { _parent.DeletedChildren.Add(item.Value); return _dict.Remove(item); }

            #endregion

            #region IEnumerable<KeyValuePair<T,K>> Members

            public IEnumerator<KeyValuePair<T, K>> GetEnumerator() { return _dict.GetEnumerator(); }

            #endregion

            #region IEnumerable Members

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _dict.GetEnumerator(); }

            #endregion
        }

        internal bool IsParentDeleted { set { _isParentDeleted = value; } }

        protected virtual bool ObjectCanDelete(IObjectContainer container) { return _isParentDeleted; }
        protected virtual bool ObjectCanNew(IObjectContainer container) { return _isParentDefined; }
    }
}
